package cn.it.Service.impl;

import cn.it.Service.IUserService;
import cn.it.domain.User;
import cn.it.mapper.UserMapper;
import cn.it.util.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class UserServiceImp implements IUserService {

    @Autowired
    UserMapper userMapper;
    @Override
    public Result login(String code, String avatarUrl, String nickName) {
        String openid = null;
        System.out.println( code+"--"+avatarUrl+"--ss--"+nickName);

        //发送网络请求查询openid
        String url="https://api.weixin.qq.com/sns/jscode2session?appid=wx1bfbbb3c4c92b3e5&secret=04e34432e50af0a5b2716579978d23c1"
                + "&js_code="+code+"&grant_type= authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        System.out.println(forEntity.getBody());
        System.out.println(forEntity.getHeaders());
        ObjectMapper jsonNode = new ObjectMapper();
        try {
            JsonNode jsonNode1 = jsonNode.readTree(forEntity.getBody());
            openid = jsonNode1.get("openid").asText();
            System.out.println(openid);
        } catch (JsonProcessingException e) {
            return new Result(201,"登陆失败",null);
        }

        if (openid!=null && !openid.equals("")){
            User user = userMapper.queryByOpenId(openid);
            System.out.println("---user---"+ user);
            if (user!=null){
                return  new Result(200,"登陆成功",user);
            }else{
                //把数据添加到数据库
                userMapper.insert(avatarUrl,nickName,openid);
                User user1 = new User();
                user1.setOpenId(openid);
                user1.setNickName(nickName);
                user1.setImageUrl(avatarUrl);
                return  new Result(200,"登陆成功",user1);
            }


        }else {
            System.out.println("----1111---");
            return new Result(201,"登陆失败",null);
        }

    }
}
